
package com.demo.controller;

import java.util.List;

import javax.ws.rs.DefaultValue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo.model.User;
import com.demo.service.IUserService;

@Controller
public class UserController {

	@Autowired
	private IUserService userService;

	@RequestMapping("/user/list.htm")
	public String list(String username,
			@RequestParam(value = "pageNo", required = false, defaultValue = "0") int pageNo,
			@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize, Model model) {
		List<User> users = userService.getUsers(username, pageNo, pageSize);
		model.addAttribute("users", users);
		model.addAttribute("username", username);
		model.addAttribute("pageNo", pageNo);
		int total = userService.count(username);
		int totalPageNo = total / pageSize;
		if (total % pageSize > 0) {
			totalPageNo++;
		}
		model.addAttribute("totalPageNo", totalPageNo);
		return "user/list";
	}

	@RequestMapping("/user/input.htm")
	public String input(@RequestParam(value = "id", required = false, defaultValue = "0") int id, Model model) {
		if (id > 0) {
			User user = userService.getUserById(id);
			model.addAttribute("user", user);
		}
		return "user/input";
	}

	@RequestMapping("/user/login_form.htm")
	public String loginForm(@RequestParam(value = "id", required = false, defaultValue = "0") int id, Model model) {
		if (id > 0) {
			User user = userService.getUserById(id);
			model.addAttribute("user", user);
		}
		return "user/login";
	}

	@RequestMapping("/user/login.htm")
	public String login(String username, String password, Model model) {
		boolean result = userService.login(username, password);
		if (result) {
			return "redirect:/user/list.htm";
		} else {
			model.addAttribute("result", result);
			return "user/login";
		}
	}

	@RequestMapping("/user/update.htm")
	public String update(User user) {
		userService.updateUser(user);
		return "redirect:/user/list.htm";
	}

	@RequestMapping("/user/delete.htm")
	public String delete(int id) {
		userService.deleteUser(id);
		return "redirect:/user/list.htm";
	}
}
